package com.dorm.cj.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestCondition {
    static final Lock LOCK = new ReentrantLock();
    static final Condition condition = LOCK.newCondition();

    public static void main(String[] args) throws InterruptedException {

        /**
         *  1.condition.await(); 必须在LOCK.lock(); LOCK.unlock();之间被调用，即调用condition.await()时，当前线程必须获取到锁
         *  2.condition.await()的线程会释放锁，线程被禁用进入睡眠，除非发生以下事件：
         *    1）其他线程调用了signal方法，当前线程被唤醒
         *    2）其他线程调用了signalAll方法，
         *    3）当前线程被中断interrupt
         *    4）发生虚假唤醒
         *
         */
        new Thread(() -> {

            try {
                LOCK.lock();
                condition.await();
                System.out.println("--------接收到signal-----");
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                LOCK.unlock();
            }
        }).start();

        System.out.println("sleep 一下，让thread进入await");
        TimeUnit.SECONDS.sleep(5);
        try {
            LOCK.lock();
            System.out.println("--------准备signal-----");
            condition.signal();
        } finally {
            LOCK.unlock();
        }
    }
}
